package com.ny.controller;

import com.ny.entity.Devices;
import com.ny.entity.Result;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/devices")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    //`http://localhost:8081/findAllDevices`
    @GetMapping("/findAllDevices")
    public Result findAllDevices(){
        return Result.success(deviceService.findAll());
    }

    /**
     * 添加设备
     * @param device 设备信息
     * @return 添加结果
     */
    @PostMapping("/addDevice")
    public Result addDevice(@RequestBody Devices device) {
        Devices savedDevice = deviceService.addDevice(device);
        return Result.success(savedDevice);
    }

    /**
     * 根据设备ID更新设备信息
     * @param device_id 设备ID
     * @param device 更新的设备信息
     * @return 更新结果
     */
    @PutMapping("/updateDevice/{device_id}")
    public Result updateDevice(@PathVariable int device_id, @RequestBody Devices device) {
        Devices updatedDevice = deviceService.updateDevice(device_id, device);
        if (updatedDevice != null) {
            return Result.success(updatedDevice);
        } else {
            return Result.success("设备不存在");
        }
    }

    /**
     * 根据设备ID删除设备
     * @param device_id 设备ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteDevice/{device_id}")
    public Result deleteDevice(@PathVariable Integer device_id) {
        deviceService.deleteDevice(device_id);
        return Result.success();
    }

    /**
     * 根据设备名称模糊查询设备
     * @param name 设备名称关键词
     * @return 查询结果
     */
    @GetMapping("/findDevicesByName/{name}")
    public Result findDevicesByName(@PathVariable String name) {
        List<Devices> devices = deviceService.findDevicesByName(name);
        return Result.success(devices);
    }
}